import Vapor
import Fluent

struct MessageController: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let userRoute = routes.grouped("api", "messages")
        userRoute.post(use: createHandler)
        userRoute.get(use: getAllHandler)
//        userRoute.get(":userID", use: getHandler)
//        userRoute.get(":machineUniqueIdentification", use: getHandlerMachineUniqueIdentification)

        userRoute.put(use: updateHandler)
        userRoute.delete(use: deleteHandler)

    }
    
    func createHandler(_ req: Request) throws -> EventLoopFuture<Message>  {
 
        let message = try req.content.decode(Message.self)
        return message.save(on: req.db).map { message }
    }
    
    func getAllHandler(_ req: Request) throws -> EventLoopFuture<[Message]> {
        Message.query(on:req.db).all()
    }
    
//    func getHandler(_ req: Request) throws -> EventLoopFuture<User> {
//        User.find(req.parameters.get("userID"), on: req.db).unwrap(or: Abort(.notFound))
//    }
    
//    func getHandlerMachineUniqueIdentification(_ req: Request) throws -> EventLoopFuture<User> {
//        let machineUniqueIdentification = req.parameters.get("machineUniqueIdentification")!
//        let uuid = "\(machineUniqueIdentification)"
//
//        return User.query(on: req.db).filter(\.$machineUniqueIdentification == uuid).first().unwrap(or: Abort(.notFound))
//    }
    
    func updateHandler(_ req: Request) throws -> EventLoopFuture<Message> {
        let data = try req.content.decode(Message.self)
        return Message.find(data.id, on: req.db).unwrap(or: Abort(.notFound)).flatMap { message in
            
            message.toAbbreviation = data.toAbbreviation
            message.fromAbbreviation = data.fromAbbreviation
            message.messageTitle = data.messageTitle
            message.messageContent = data.messageContent
            message.messageType = data.messageType
            message.isSeen = data.isSeen
            message.sendDateTime = data.sendDateTime
            message.seenDateTime = data.seenDateTime
            message.isHighPriority = data.isHighPriority
            message.linkedTo = data.linkedTo
            message.additionalInformation = data.additionalInformation
            
            return message.save(on: req.db).map { return message }

        }
    }
    
    func deleteHandler(_ req: Request) throws -> EventLoopFuture<HTTPStatus> {
        let data = try req.content.decode(Message.self)
        
        return Message.find(data.id, on: req.db).unwrap(or: Abort(.notFound)).flatMap { message in
            message.delete(on: req.db).transform(to: .noContent)
        }

    }
    

}


